import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Layout,
  Card,
  List,
  Avatar,
  Button,
  Input,
  Modal,
  Form,
  message,
  Tabs,
  Badge,
  Space,
  Typography,
  Divider,
  Popconfirm,
  Empty,
  Spin
} from 'antd';
import {
  UserAddOutlined,
  SearchOutlined,
  UserOutlined,
  MessageOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined,
  TeamOutlined
} from '@ant-design/icons';
import { friendsService, chatService } from '../services/api';

const { Title, Text } = Typography;

interface Friend {
  id: number;
  username: string;
  email: string;
  avatar?: string;
  bio?: string;
  is_online?: boolean;
  last_seen_at?: string;
  status: string;
  friendship_created_at: string;
}

interface FriendRequest {
  id: number;
  user_id: number;
  username: string;
  email: string;
  avatar?: string;
  bio?: string;
  status: string;
  created_at: string;
}

interface SearchUser {
  id: number;
  username: string;
  email: string;
  avatar?: string;
  bio?: string;
  is_online?: boolean;
  friendship_status?: string;
}

const Friends: React.FC = () => {
  const navigate = useNavigate();
  const [friends, setFriends] = useState<Friend[]>([]);
  const [requests, setRequests] = useState<FriendRequest[]>([]);
  const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchLoading, setSearchLoading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchModalVisible, setSearchModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('friends');
  const [friendSearchQuery, setFriendSearchQuery] = useState('');

  // 页面初始化
  useEffect(() => {
    loadFriends();
    loadRequests();
    
    // 设置用户为在线状态
    friendsService.updateOnlineStatus(true).catch(error => {
      console.log('更新在线状态失败:', error);
    });
    
    // 定期更新在线状态（每30秒）
    const onlineInterval = setInterval(() => {
      friendsService.updateOnlineStatus(true).catch(error => {
        console.log('定期更新在线状态失败:', error);
      });
    }, 30000);
    
    // 页面卸载时设置为离线
    const handleBeforeUnload = () => {
      friendsService.updateOnlineStatus(false).catch(error => {
        console.log('设置离线状态失败:', error);
      });
    };
    
    window.addEventListener('beforeunload', handleBeforeUnload);
    
    return () => {
      clearInterval(onlineInterval);
      window.removeEventListener('beforeunload', handleBeforeUnload);
      friendsService.updateOnlineStatus(false).catch(error => {
        console.log('组件卸载时设置离线状态失败:', error);
      });
    };
  }, []);

  // 加载好友列表
  const loadFriends = async () => {
    try {
      setLoading(true);
      const response = await friendsService.getFriends();
      if (response && (response as any).success) {
        setFriends((response as any).friends || []);
      }
    } catch (error: any) {
      console.error('加载好友列表失败:', error);
      message.error('加载好友列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载好友请求
  const loadRequests = async () => {
    try {
      const response = await friendsService.getFriendRequests();
      if (response && (response as any).success) {
        setRequests((response as any).requests || []);
      }
    } catch (error: any) {
      console.error('加载好友请求失败:', error);
    }
  };

  // 搜索用户
  const handleSearch = async (query: string) => {
    if (!query.trim()) {
      setSearchResults([]);
      return;
    }

    try {
      setSearchLoading(true);
      const response = await friendsService.searchUsers(query);
      if (response && (response as any).success) {
        setSearchResults((response as any).users || []);
      }
    } catch (error: any) {
      console.error('搜索用户失败:', error);
      message.error('搜索用户失败');
    } finally {
      setSearchLoading(false);
    }
  };

  // 发送好友请求
  const handleSendRequest = async (userId: number) => {
    try {
      const response = await friendsService.sendFriendRequest(userId);
      if (response && (response as any).success) {
        message.success('好友请求已发送');
        handleSearch(searchQuery); // 刷新搜索结果
      }
    } catch (error: any) {
      console.error('发送好友请求失败:', error);
      message.error(error.response?.data?.message || '发送好友请求失败');
    }
  };

  // 处理好友请求
  const handleRequestAction = async (requestId: number, action: 'accept' | 'reject') => {
    try {
      const response = await friendsService.handleFriendRequest(requestId, action);
      if (response && (response as any).success) {
        message.success(action === 'accept' ? '好友请求已接受' : '好友请求已拒绝');
        loadRequests();
        loadFriends();
      }
    } catch (error: any) {
      console.error('处理好友请求失败:', error);
      message.error('处理好友请求失败');
    }
  };

  // 删除好友
  const handleDeleteFriend = async (friendId: number) => {
    try {
      const response = await friendsService.deleteFriend(friendId);
      if (response && (response as any).success) {
        message.success('好友已删除');
        loadFriends();
      }
    } catch (error: any) {
      console.error('删除好友失败:', error);
      message.error('删除好友失败');
    }
  };

  // 开始私聊
  const handleStartChat = async (friendId: number) => {
    try {
      const response = await chatService.createPrivateChat(friendId);
      if (response && (response as any).success) {
        const roomId = (response as any).room_id;
        // 跳转到聊天页面，并传递房间ID
        navigate(`/chat?room=${roomId}`);
      } else {
        message.error('创建私聊失败');
      }
    } catch (error: any) {
      console.error('创建私聊失败:', error);
      message.error('创建私聊失败');
    }
  };

  // 获取好友状态显示
  const getFriendStatusText = (status: string) => {
    switch (status) {
      case 'accepted':
        return '已添加';
      case 'pending':
        return '待确认';
      case 'blocked':
        return '已屏蔽';
      default:
        return '未知';
    }
  };

  // 获取好友状态颜色
  const getFriendStatusColor = (status: string) => {
    switch (status) {
      case 'accepted':
        return 'green';
      case 'pending':
        return 'orange';
      case 'blocked':
        return 'red';
      default:
        return 'default';
    }
  };

  return (
    <div style={{ 
      background: 'transparent',
      height: '100%',
      padding: '0',
      overflow: 'hidden'
    }}>
      <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
        {/* 页面标题 */}
        <div style={{ marginBottom: '30px' }}>
          <Title level={2} style={{ color: '#2c3e50', marginBottom: '10px' }}>
            <TeamOutlined style={{ marginRight: '10px' }} />
            好友管理
          </Title>
          <Text style={{ color: '#666', fontSize: '16px' }}>
            管理您的好友关系，与学习伙伴保持联系
          </Text>
        </div>


        {/* 主要内容 */}
        <div style={{ height: 'calc(100% - 120px)', overflow: 'hidden' }}>
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            style={{ height: '100%' }}
            tabBarStyle={{ marginBottom: '16px' }}
          items={[
            {
              key: 'friends',
              label: (
                <span>
                  我的好友
                  {friends.length > 0 && (
                    <span style={{ 
                      marginLeft: '8px', 
                      fontSize: '12px', 
                      color: '#666',
                      backgroundColor: '#f0f0f0',
                      padding: '2px 6px',
                      borderRadius: '10px'
                    }}>
                      {friends.length}
                    </span>
                  )}
                </span>
              ),
              children: (
                <Card style={{ height: 'calc(100% - 60px)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', overflowY: 'auto' }}>
                  {loading ? (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                      <Spin size="large" />
                    </div>
                  ) : friends.length === 0 ? (
                    <div style={{ textAlign: 'center', padding: '60px 20px' }}>
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="还没有好友，快去添加一些学习伙伴吧！"
                      />
                      <div style={{ marginTop: '24px' }}>
                        <Button
                          type="primary"
                          size="large"
                          icon={<UserAddOutlined />}
                          onClick={() => setSearchModalVisible(true)}
                        >
                          添加好友
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div>
                      {/* 好友搜索框 */}
                      <div style={{ marginBottom: '16px', padding: '0 4px' }}>
                        <Input.Search
                          placeholder="搜索好友..."
                          value={friendSearchQuery}
                          onChange={(e) => setFriendSearchQuery(e.target.value)}
                          style={{ width: '100%', maxWidth: '300px' }}
                          allowClear
                        />
                      </div>
                      <List
                        dataSource={friends.filter(friend => 
                          !friendSearchQuery || 
                          friend.username.toLowerCase().includes(friendSearchQuery.toLowerCase()) ||
                          friend.email.toLowerCase().includes(friendSearchQuery.toLowerCase())
                        )}
                        renderItem={(friend) => (
                        <List.Item
                          actions={[
                            <Button
                              key="chat"
                              type="link"
                              icon={<MessageOutlined />}
                              onClick={() => handleStartChat(friend.id)}
                            >
                              私聊
                            </Button>,
                            <Popconfirm
                              key="delete"
                              title="确定要删除这个好友吗？"
                              onConfirm={() => handleDeleteFriend(friend.id)}
                              okText="确定"
                              cancelText="取消"
                            >
                              <Button
                                type="link"
                                danger
                                icon={<DeleteOutlined />}
                              >
                                删除
                              </Button>
                            </Popconfirm>
                          ]}
                        >
                          <List.Item.Meta
                            avatar={
                              <Avatar 
                                src={friend.avatar} 
                                icon={<UserOutlined />}
                                size="large"
                              />
                            }
                            title={
                              <Space>
                                <span>{friend.username}</span>
                                {friend.is_online ? (
                                  <Badge status="success" text="在线" />
                                ) : (
                                  <span style={{ color: '#999', fontSize: '12px' }}>
                                    离线
                                  </span>
                                )}
                              </Space>
                            }
                            description={
                              <div>
                                <div>{friend.email}</div>
                                {friend.bio && <div style={{ color: '#666' }}>{friend.bio}</div>}
                                <div style={{ color: '#999', fontSize: '12px' }}>
                                  添加时间: {new Date(friend.friendship_created_at).toLocaleDateString()}
                                </div>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                    </div>
                  )}
                  </div>
                </Card>
              )
            },
            {
              key: 'requests',
              label: (
                <span>
                  好友请求
                  <Badge count={requests.length} style={{ marginLeft: '8px' }} />
                </span>
              ),
              children: (
                <Card style={{ height: 'calc(100% - 60px)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', overflowY: 'auto' }}>
                  {requests.length === 0 ? (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description="暂无好友请求"
                    />
                  ) : (
                    <List
                      dataSource={requests}
                      renderItem={(request) => (
                        <List.Item
                          actions={[
                            <Button
                              key="accept"
                              type="primary"
                              icon={<CheckOutlined />}
                              onClick={() => handleRequestAction(request.id, 'accept')}
                            >
                              接受
                            </Button>,
                            <Button
                              key="reject"
                              icon={<CloseOutlined />}
                              onClick={() => handleRequestAction(request.id, 'reject')}
                            >
                              拒绝
                            </Button>
                          ]}
                        >
                          <List.Item.Meta
                            avatar={
                              <Avatar 
                                src={request.avatar} 
                                icon={<UserOutlined />}
                                size="large"
                              />
                            }
                            title={request.username}
                            description={
                              <div>
                                <div>{request.email}</div>
                                {request.bio && <div style={{ color: '#666' }}>{request.bio}</div>}
                                <div style={{ color: '#999', fontSize: '12px' }}>
                                  请求时间: {new Date(request.created_at).toLocaleDateString()}
                                </div>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                  )}
                  </div>
                </Card>
              )
            }
          ]}
        />
        </div>

        {/* 右下角浮动添加按钮 - 当有好友时显示 */}
        {friends.length > 0 && (
          <div style={{
            position: 'fixed',
            bottom: '24px',
            right: '24px',
            zIndex: 1000
          }}>
            <Button
              type="primary"
              shape="circle"
              size="large"
              icon={<UserAddOutlined />}
              onClick={() => setSearchModalVisible(true)}
              style={{
                width: '56px',
                height: '56px',
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
              }}
            />
          </div>
        )}

        {/* 搜索用户模态框 */}
        <Modal
          title="搜索用户"
          open={searchModalVisible}
          onCancel={() => {
            setSearchModalVisible(false);
            setSearchQuery('');
            setSearchResults([]);
          }}
          footer={null}
          width={600}
        >
          <div style={{ marginBottom: '16px' }}>
            <Input.Search
              placeholder="输入用户名或邮箱搜索..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onSearch={handleSearch}
              loading={searchLoading}
            />
          </div>

          {searchLoading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin />
            </div>
          ) : searchResults.length === 0 && searchQuery ? (
            <Empty description="未找到相关用户" />
          ) : (
            <List
              dataSource={searchResults}
              renderItem={(user) => (
                <List.Item
                  actions={[
                    user.friendship_status === 'accepted' ? (
                      <Badge status="success" text="已是好友" />
                    ) : user.friendship_status === 'pending' ? (
                      <Badge status="processing" text="请求已发送" />
                    ) : (
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => handleSendRequest(user.id)}
                      >
                        添加好友
                      </Button>
                    )
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar 
                        src={user.avatar} 
                        icon={<UserOutlined />}
                      />
                    }
                    title={user.username}
                    description={
                      <div>
                        <div>{user.email}</div>
                        {user.bio && <div style={{ color: '#666' }}>{user.bio}</div>}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          )}
        </Modal>
      </div>
    </div>
  );
};

export default Friends;